package com.webchat.connect.messagequeue.consumer.service;


import com.google.common.collect.Sets;
import com.webchat.common.constants.ConnectConstants;
import com.webchat.common.enums.ChatMessageTypeEnum;
import com.webchat.common.util.JsonUtil;
import com.webchat.connect.service.AccountService;
import com.webchat.connect.websocket.handler.ChatWebSocketEndPointServletHandler;
import com.webchat.domain.vo.request.mess.MessageNotifyVO;
import com.webchat.domain.vo.response.UserBaseResponseInfoVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

/**
 * 处理群聊多人音视频呼叫消息
 */
@Service
public class GroupVideoCallConsumeService {

    @Autowired
    private AccountService accountService;

    /**
     * 处理群聊多人音视频呼叫消息
     *
     * @param message
     */
    public void consume(String message) {

        if (StringUtils.isBlank(message)) {
            // TODO, 预警
            return;
        }
        MessageNotifyVO messageBase = JsonUtil.fromJson(message, MessageNotifyVO.class);
        Assert.notNull(messageBase, "群聊多人音视频呼叫消息反序列化失败！");
        // 这里的senderId不是音视频的实际发起人，而是群聊id（消息代理人）
        String groupId = messageBase.getSenderId();
        String senderId = messageBase.getProxySenderId();
        // 获取群聊下所有用户
        Set<String> userIds = accountService.getGroupUserIds(groupId);
        if (CollectionUtils.isEmpty(userIds)) {
            // 群聊下没有任何用户
            return;
        }
        Map<String, UserBaseResponseInfoVO> accountMap = accountService.batchGet(Sets.newHashSet(senderId, groupId));
        if (accountMap == null) {
            // TODO, 预警
            return;
        }

        UserBaseResponseInfoVO group = accountMap.get(groupId);
        UserBaseResponseInfoVO sender = accountMap.get(senderId);

        /**
         * 走client最外层对话ws推送音视频呼叫提醒
         */
        Set<String> bizCodes = ConnectConstants.ConnectBiz.getBizCode(ConnectConstants.BizEnum.INDEX);
        for (String bizCode : bizCodes) {
            for (String userId : userIds) {
                if (ObjectUtils.equals(userId, senderId)) {
                    continue;
                }
                /**
                 * 群场景推送，类如用户多端登录，同时移动、PC在线，多端需要同时收到音视频邀请通知
                 */
                WebSocketSession session = ChatWebSocketEndPointServletHandler.getSession(bizCode, userId);
                if (session == null || !session.isOpen()) {
                    continue;
                }
                MessageNotifyVO videoCallMessage = new MessageNotifyVO();
                videoCallMessage.setSender(group);
                videoCallMessage.setProxySender(sender);
                videoCallMessage.setType(ChatMessageTypeEnum.GROUP_VIDEO_CALL.getType());
                try {
                    session.sendMessage(new TextMessage(JsonUtil.toJsonString(videoCallMessage)));
                } catch (IOException e) {
                    // 这里不能跑出异常，否则会中断整个推送任务
                    // TODO 处理策略：重拾一次/预警通知

                }
            }

        }

    }
}
